package com.example.interviewrecorder.components

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import androidx.appcompat.app.ActionBar
import com.example.interviewrecorder.LyyApplicaiton
import com.example.interviewrecorder.R
import com.example.interviewrecorder.view.AboutActivity
import com.example.interviewrecorder.databinding.LyyTitlebarBinding
import com.example.interviewrecorder.databinding.MenuBinding
import com.example.interviewrecorder.utils.LyyActivityCollector
import com.example.interviewrecorder.utils.ScreenUtil

class LyyTitlebar(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {
    private var binding: LyyTitlebarBinding =
        LyyTitlebarBinding.inflate(LayoutInflater.from(context), this, true)
    private var popupWindow: PopupWindow? = null

    init {
        binding.backIv.setOnClickListener {
            val act = context as Activity
            act.finish()
        }

        binding.moreIv.setOnClickListener {
            showMenu(it.context)
        }

        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.LyyTitlebar)
        val title = typedArray.getString(R.styleable.LyyTitlebar_title)
        val isShowMore = typedArray.getBoolean(R.styleable.LyyTitlebar_isShowMore, true)
        binding.titleTv.text = title ?: LyyApplicaiton.context.getString(R.string.title_text)
        binding.moreIv.visibility = if (isShowMore) View.VISIBLE else View.GONE
        typedArray.recycle()
    }

    private fun showMenu(context: Context) {
        val popupWindowViewBinding = MenuBinding.inflate(LayoutInflater.from(context), null, false)
        popupWindow = PopupWindow(
            popupWindowViewBinding.root,
            ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.WRAP_CONTENT,
            true
        )
        popupWindow?.showAsDropDown(binding.moreIv, 0, ScreenUtil.convertDpToPx(12f))
        popupWindowViewBinding.exitLl.setOnClickListener {
            showInfo(
                title = LyyApplicaiton.context.getString(R.string.tip_title),
                content = LyyApplicaiton.context.getString(R.string.confirm_exit_app),
                onPositiveBtnClick = { LyyActivityCollector.finishAll() })
        }
        popupWindowViewBinding.aboutLl.setOnClickListener {
            getContext().startActivity(Intent(getContext(), AboutActivity::class.java))
        }
        popupWindowViewBinding.root.setOnTouchListener { _, _ ->
            popupWindow?.let {
                if (it.isShowing) {
                    it.dismiss()
                    popupWindow = null
                }
            }
            false
        }
    }
}